package phoenix.web.test_objects;

import java.awt.Dimension;
import java.util.Map;

import phoenix.core.PhoenixManager;
import phoenix.core.base.extensions.TestBaseWebExt;
import phoenix.core.data_models.UserProfileDataModel.LookingFor;
import phoenix.web.test_objects.data_providers.SearchDataProviders;
import core.config.Config;

public class SearchTests extends TestBaseWebExt
{
	public SearchTests(PhoenixManager p_phoenix)
	{
		super(p_phoenix);
	}

	public MyProfileTests myProfileTests = new MyProfileTests(manager);
	// Data
	public SearchDataProviders dataProviders = new SearchDataProviders(manager);

	/**
	 * @param p_lookingForParams
	 */
	public void searchAtFunnelTest(LookingFor p_lookingForParams)
	{
		try
		{
			wd().openAutologin(testUser());
			// Goes to funnel page
			wd().openPage("/funnel");
			page().searchPage().waitForPageLoad();
			// Fill funnel page
			page().funnelPage().fillStepOne(testUser().getScreenname(), p_lookingForParams);
			page().funnelPage().clickNextStep();

			if (page().funnelPage().isLocationSuggestPresent(p_lookingForParams.location))
			{
				wd().wait(2);
				page().funnelPage().clickLocationSuggest(p_lookingForParams.location);
			}

			if (wd().isUrlContains("photoUploadMotivation", false))
			{
				page().funnelPage().clickSave();
			}

			// Do test
			this.searchResultsTest(p_lookingForParams, "searchAtFunnelTest");
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("searchAtFunnelTest " + p_ex.toString());
		}

		test().forErrors();
	}

	public void searchAtToolbarTest(LookingFor p_lookingForParams)
	{
		try
		{
			// Login to site by auto login
			wd().openURL(testUser().getAutologin());
			page().searchPage().waitForPageLoad();
			// Fills up Looking for at Toolbar
			page().searchPage().setSearchLookingFor(p_lookingForParams);

			// Do test
			this.searchResultsTest(p_lookingForParams, "searchAtToolbarTest");
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("searchAtToolbarTest " + p_ex.toString());
		}

		test().forErrors();
	}

	public void searchAtProfileTest(LookingFor p_lookingForParams)
	{
		try
		{
			// Fill up Looking For form
			wd().openAutologin(testUser());
			wd().openPage("/profile");
			page().myProfilePage().waitForPageLoad();

			if (manager.isBN() || manager.isWB() || manager.isMD())
			{
				page().myProfilePage().clickEditLookingForInfo();
			}

			if (manager.isCNF() || manager.isLGW() || manager.isNF())
			{
				page().myProfilePage().clickEditLookingFor();
			}

			page().myProfilePage().setFormLookingFor(p_lookingForParams);
			page().myProfilePage().submitLookingForm();
			// Test Search
			wd().openURL(testModel().getSiteURL() + "/search");
			this.searchResultsTest(p_lookingForParams, "searchAtProfileTest");
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("searchAtProfileTest " + p_ex.toString());
		}

		test().forErrors();
	}

	public void countryTest(String p_data, String p_errorMessage)
	{
		// Country check
		if (p_data != "" && p_data != null)
		{
			test().assertEquals(this.trimCountryName(p_data), testUser().getCountry(), p_errorMessage.replace("Test message", "Country alert"));
			log().info(p_errorMessage.replace("Test message", "Country test"));
		}
		else
		{
			log().warn("County is empty ? " + p_errorMessage.replace("Test message", "Country warning"));
		}
	}

	public void distanceTest(String p_data, LookingFor p_lookingForParams, String p_errorMessage)
	{
		p_data = p_data.substring(0, p_data.length()).trim();

		if (p_data != "" && p_data != null)
		{

			if (manager.isFlirt() || manager.isWB() || manager.isBN())
			{
				log().warn("Skip 'Distance'");
				return;
			}

			Integer p_distance = Integer.parseInt(p_lookingForParams.distance);
			p_distance = p_distance + 5; // Required for correct validation

			Integer p_point = p_data.indexOf(".");
			p_data = (p_point == -1) ? p_data : p_data.substring(0, p_point);

			// Verifies that user radius is lower than given val
			test().forLowerOrEqual(p_data, p_distance.toString(), p_errorMessage.replace("Test message", "Distance alert"));
			log().info(p_errorMessage.replace("Test message", "Distance test"));
		}
		else
		{
			log().warn("distance is empty ? : " + p_errorMessage.replace("Test message", "Distance warning"));
		}
	}

	/**
	 * @param p_age
	 * @param p_lookingForParams
	 * @param p_errorMessage
	 */
	public void ageTest(String p_age, LookingFor p_lookingForParams, String p_errorMessage)
	{
		if (p_age != null && p_age != "")
		{
			test().forLowerOrEqual(p_age.substring(0, 2).trim(), p_lookingForParams.ageTo, p_errorMessage.replace("Test message", "Age alert"));
			test().forGreaterOrEqual(p_age.substring(0, 2).trim(), p_lookingForParams.ageFrom, p_errorMessage.replace("Test message", "Age alert"));
			log().info(p_errorMessage.replace("Test message", "Age test"));
		}
		else
		{
			log().warn("Given age is null ? :" + p_errorMessage.replace("Test message", "Age warning"));
		}
	}

	/**
	 * @param p_lookingForParams
	 * @param p_testPhase
	 */
	private void searchResultsTest(LookingFor p_lookingForParams, String p_testPhase)
	{
		try
		{
			page().searchPage().waitForPageLoad();
			page().searchPage().scrollSearch();

			if (manager.isFlirt())
			{
				try
				{
					// Set hot status
					page().menuPage().setNaughtyMode(3);
				}
				catch (Exception p_ex)
				{
					log().warn("Unable to set naughty mode");
				}
			}

			Map<Integer, String[]> p_searchData = page().searchPage().getSearchResultsData(p_lookingForParams);

			if (p_searchData.size() == 0)
			{
				throw new Exception("There is no users found in search");
			}

			/**
			 * Verification of avatar image size at user profile for free and paid user
			 */
			this.avatarSizeTest();

			Integer numberOfPassedTests = 0;
			for (Map.Entry<Integer, String[]> entry : p_searchData.entrySet())
			{
				/**
				 * 0 = Age
				 * 1 = Distance
				 * 2 = Country
				 * 3 = ScreenName
				 * 4 = ID
				 */
				String p_data[] = entry.getValue();

				if (p_data[0].isEmpty())
				{
					log().warn("Unable to check Age on profile " + p_data[4]);
					continue;
				}
				else if (p_data[1].isEmpty())
				{
					log().warn("Unable to check Distance on profile " + p_data[4]);
					continue;
				}
				else if (p_data[2].isEmpty())
				{
					log().warn("Unable to check Country on profile " + p_data[4]);
					continue;
				}
				else if (p_data[3].isEmpty())
				{
					log().warn("Unable to check Name on profile " + p_data[4]);
					continue;
				}

				String l_errorMessageTemp = p_testPhase + " Test message : Screen name : " + p_data[3] + " ID: " + p_data[4] + " | Search params (FROM: "
					+ p_lookingForParams.ageFrom
					+ " TO: " + p_lookingForParams.ageTo + " in radius " + p_lookingForParams.distance + ")";

				// Age
				this.ageTest(p_data[0], p_lookingForParams, l_errorMessageTemp);
				// Distance
				this.distanceTest(p_data[1], p_lookingForParams, l_errorMessageTemp);
				// Country
				this.countryTest(p_data[2], l_errorMessageTemp);

				numberOfPassedTests++;
			}

			page().searchPage().getNumberUsersInSearch();
			log().info("Tests passed " + numberOfPassedTests.toString());

			if (log().isErrors())
			{
				log().errorAndScreen("Errors " + p_testPhase);
			}
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen(p_testPhase + " " + p_ex.toString());
		}
	}

	private String trimCountryName(String p_locationString)
	{
		String country = (p_locationString.indexOf(this.getCountryTextDevider()) == -1) ?
			p_locationString :
			p_locationString.substring(0, p_locationString.indexOf(this.getCountryTextDevider()));

		if (manager.isWB() || manager.isBN())
		{
			// incoming value is "UKLondon"
			country = country.substring(0, manager.testModel().getLocation().length());
		}

		return country;
	}

	private String getCountryTextDevider()
	{
		if (manager.isFlirt())
		{
			return ",";
		}
		else
		{
			return "|";
		}
	}

	/**
	 * Checks size of avatar image
	 */
	public void avatarSizeTest()
	{
		log().info("Test 'avatarSizeTest' run...");

		if (manager.isFlirt() || manager.isWB() || manager.isBN() || manager.isMD())
		{
			log().info("On site " + testModel().getSiteName() + " avatar size test skipped...");
			return;
		}

		Dimension imageSize = null;
		try
		{
			imageSize = page().searchPage().avatarSizeTest();
			log().info("Value of imageSize: " + imageSize);

			if (testUser().getMembershipStatus() == 1)
			{
				// Checks that image is larger than expected size
				test().forGreaterOrEqual(imageSize.height, 90, "Compare avatar size at search page for free user");

			}
			else if (testUser().getMembershipStatus() >= 2)
			{
				// Checks that image is larger than expected size
				test().forGreaterOrEqual(imageSize.height, 180, "Compare avatar size at search page for paid user");
			}

		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("avatarSizeTest " + p_ex.toString());
		}
	}

	/**
	 * Count user at search after funnel
	 */
	public void countUsersAtSearchTest()
	{
		int p_users = 0;

		try
		{
			wd().openAutologin(testUser());
			page().searchPage().waitForPageLoad();
			wd().wait(5);
			manager.web().searchPage().scrollSearch();
			p_users = page().searchPage().getNumberUsersInSearch();

			if (Config.BUILD.equals(Config.BUILD_REL))
			{
				manager.log().warn("We do skip for search users on rel, found number is " + p_users);
				return;
			}

			if (p_users == 0)
			{
				log().errorAndScreen("There are no users found in search");
			}

			if (p_users < 40)
			{
				log().errorAndScreen("We do expect more than 40 users at search page after funnel");
			}
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("countUsersAtSearchTest: " + p_ex.toString());
		}
		finally
		{
			test().forErrors();
		}
	}

}
